package com.example.java_websocket.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;

/**
 * 说明：spring 应用上下文持有者
 *
 * @author 钟波notebook
 * @since 2020年01月25日 星期六 22:05:11
 */
@Component
@Slf4j
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("SpringContextHolder set applicationContext : {}", applicationContext);
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> tClass) {
        if (null == context) {
            log.error("SpringContextHolder context is null!");
            return null;
        }
        return context.getBean(tClass);
    }

    public static int exit() {
        Executors.defaultThreadFactory().newThread(() -> {
            int exit = SpringApplication.exit(context, () -> 0);
            log.info("程序退出: {}", exit);
            System.exit(0);
        }).start();
        log.info("程序即将退出...");
        return 0;
    }

}
